package web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import beans.Rate;
import beans.User;

import dao.RateDAO;
import web.LoggedUser;

public class RateController {
	private RateDAO rateDAO;
	private LoggedUser loggedUser;

	public void setRateDAO(RateDAO rateDAO) {
		this.rateDAO = rateDAO;
	}

	public void setLoggedUser(LoggedUser loggedUser) {
		this.loggedUser = loggedUser;
	}

	@RequestMapping(value = "/rateRestaurantId={restaurantId}")
	public ModelAndView rate(@PathVariable("restaurantId") int id,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		User user = loggedUser.getLoggedUser();
		Rate rate = rateDAO.findRate(user, id);
		if (rate == null) {
			int rating;
			if (!(request.getParameter("group1").equalsIgnoreCase("brak oceny"))) {
				rating = Integer.parseInt(request.getParameter("group1"));
				rate = new Rate();
				rate.setRate(rating);
				rate.setUsername(user.getUsername());
				rate.setRestaurant_id(id);
				rateDAO.saveRate(rate);
			}
		} else {
			if (request.getParameter("group1").equalsIgnoreCase("brak oceny")) {
				rateDAO.deleteRate(rate);
			} else {
				int rating = Integer.parseInt(request.getParameter("group1"));
				rate.setRate(rating);
				rateDAO.updateRate(rate);

			}
			
		}
		return new ModelAndView("redirect:restaurantid=" + id + ".htm");
	}
}
